package com.zxk.version3.provider;

import com.zxk.version3.core.RpcRequest;
import com.zxk.version3.core.RpcResponse;
import lombok.AllArgsConstructor;

import java.io.*;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.net.Socket;


/**
 * @author： 朱小康
 * @create： 2024/5/29 17:51
 */
@AllArgsConstructor
public class WorkThread implements Runnable {

    private Socket socket;
    private ServiceProvider serviceProvider;




    @Override
    public void run() {
        try {
            InputStream inputStream = socket.getInputStream();
            OutputStream outputStream = socket.getOutputStream();
            ObjectInputStream objectInputStream = new ObjectInputStream(inputStream);
            ObjectOutputStream objectOutputStream = new ObjectOutputStream(outputStream);

            RpcRequest rpcRequest = (RpcRequest) objectInputStream.readObject();
            //调用方法获取返回值
            RpcResponse rpcResponse = getResponse(rpcRequest);
            //写入到客户端
            objectOutputStream.writeObject(rpcResponse);
            objectOutputStream.flush();


        } catch (IOException | ClassNotFoundException e) {
            e.printStackTrace();
        }


    }

    private RpcResponse getResponse(RpcRequest rpcRequest) {
        //获取服务名
        String interfaceName = rpcRequest.getInterfaceName();

        //获取对应的实现
        Object service = serviceProvider.getService(interfaceName);

        //反射调用方法执行
        try {
            Method method = service.getClass().getMethod(rpcRequest.getMethodName(), rpcRequest.getParamsTypes());
            Object invoke = method.invoke(service, rpcRequest.getArgs());
            return RpcResponse.success(invoke);
        } catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException e) {
            e.printStackTrace();
            return RpcResponse.fail();
        }
    }
}
